import React from 'react'
import { createForm } from 'rc-form'
import { actions } from 'mirrorx'
import { List, InputItem, Flex, DatePicker, Picker,Toast } from 'antd-mobile'
import T from '../../lib/T'
import {API} from '../api'
import {Globle} from './Dictionaries';


class App extends React.Component {
  constructor (props) {
    super(props)


    const policyNo = T.urlQuery('policyNo') || '';
    const insuredName = T.urlQuery('insuredName') || ''
    const insuredId = T.urlQuery('insuredId') || ''

    this.state = {
      errorMap: {},
      windowHeight: '400px',
      dateValue: T.formatDate(Globle.dateFormat, new Date()),
      insuredArray: (insuredName&&insuredId) ? [{label:insuredName,value:insuredId}] : [],
      disableInput:true,
      infoValues: {
        policyNo: policyNo,
        insuredName:insuredName
      }
    }

    this.keyCodes = [
      {
        keycode: 'reporterName',
        text: 'Name',
        message: 'Please input name',
        rules: [
          { required: true, message: 'Please input name' }
        ]
      },
      {
        keycode: 'reporterPhone',
        text: 'Phone Number',
        rules: [
          { required: true, message: 'Please input phone number' },
          { pattern: /^[0-9+\(\)]*$/, message: 'The phone number is not valid' }
        ]
      },
      {
        keycode: 'reporterEmail',
        text: 'Email Address',
        type: 'email',
        rules: [
          { required: true, message: 'Please input email address' },
          { pattern: /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/, message: 'The email address is not valid' }
        ]
      }
    ]

    this.handleSubmit = this.handleSubmit.bind(this)
    this.onErrorClick = this.onErrorClick.bind(this)
    this.onDateOk = this.onDateOk.bind(this)
  }

  componentDidMount () {
    // 保单号+被保人 从链接获取
    let windowHeight = T.getScreenHeight()
    let infoValues = JSON.parse(T.sessionStorage.get('infoValues')) || this.state.infoValues || {}
    let dateValue = T.formatDate(Globle.dateFormat, new Date())
    if (infoValues.accidentDate) {
      dateValue = T.formatDate(Globle.dateFormat, new Date(infoValues.accidentDate))
    }
    // 如果连接带有保单号 直接查询被保险人
    this.searchPInfo(infoValues.policyNo)
    //延迟赋值缓存值
    window.setTimeout(()=>{
      this.setState({
        windowHeight,
        infoValues,
        dateValue
      })
    },100)
  }

  handleSubmit (e) {
    this.props.form.validateFields((error, values) => {
      var errorMap = {}
      if (error) {
        for (var key in error) {
          errorMap[key] = 1
        }
        this.setState({
          errorMap
        })
        console.warn('The form is error:',error,errorMap);
        //弹出第一个error 提示
        this.onErrorClick(Object.keys(error)[0])
      } 
      else {
        const insuredModel = this.state.insuredArray.filter((item)=>{
          return item.value == values.insuredId
        })[0];
        values.insuredName = insuredModel ? insuredModel.label : ''
        values.policyNo = this.state.infoValues.policyNo
        values.accidentDate = values.accidentDate.getTime() // 时间转时间戳
        // 数据放到内存管理
        T.sessionStorage.set('infoValues', values)
        actions.routing.push({
          pathname: '/poc-claim-upload'
        })
      }
    })
  }

  onErrorClick (keyCode) {
    const { getFieldError } = this.props.form
    let msg = getFieldError(keyCode)
    if (msg) {
      T.showError(msg.join(','))
    }
  }

  
  onDateOk (val) {
    if (val) {
      this.props.form.setFieldsValue({
        accidentDate: val
      })
      let dateValue = T.formatDate(Globle.dateFormat, new Date(val)) || ''
      this.setState({
        dateValue
      })
    }
  }

  dateFormat (date) {
    if (date) {
      return T.formatDate(Globle.dateFormat, new Date(date)) || ''
    }
  }

  /**
   *
   * 非受控组件 需要自己设置值
   * @memberof App
   */
  policyChange =(value)=> {
    this.setState({
      infoValues: {
        policyNo: value
      }
    })
  }

  searchPInfo =(value)=>{
    if (value){
      //调用查询接口 查询信息
      const queryDTO = T.fetch2({
        loading: true,
        domainType:'apiclaim',
        url: API.queryPolicyInsureds.path,
        data: {policyNo:value}
      })
      queryDTO.then((model)=>{
        const insuredsModel= model.data || []
        //处理接口数据 包装成 label value
        if (insuredsModel.length >0 ){
          const pickerModel =  insuredsModel.map((item)=>{
            return {label:item.insuredName,value:item.insuredId}
          })
          //显示被保险人选择  启用所有输入框
          this.setState({
            insuredArray:pickerModel,
            disableInput:false
          })
        }
        else {
          //提示未查到相关信息
          Toast.fail('This policy number doesn\'t exist');
          //禁用所有输入框
          this.setState({
            insuredArray:[],
            disableInput:true
          })
        }
      })
    }
  }

  render () {
    const { errorMap, windowHeight, infoValues } = this.state
    const { getFieldProps } = this.props.form
    const nowTimeStamp = Date.now()
    const nowDate = new Date(nowTimeStamp)  //当前日期
    const minDate = new Date(nowTimeStamp - 90 * 24 * 60 * 60 * 1000) //最小日期
    let defaultDate = infoValues.accidentDate ? new Date(infoValues['accidentDate']) : null

    return (
      <div className='poc-claim' style={{ minHeight: windowHeight }}>
        <div className='f26 fc8 pl30  pb20 pt40' style={{ background: '#F7F9FB' }}>Claimant Info</div>
        <List className='input-list'>
          {/* 保单号输入框 单独 */}
          <InputItem
            {...getFieldProps('policyNo', {
              initialValue: infoValues['policyNo'] || '',
              rules: {
                required: true, message: 'Please input Policy No'
              }
            })}
            maxLength={50}
            labelNumber={5}
            error={errorMap['policyNo']}
            onErrorClick={() => this.onErrorClick('policyNo')}
            placeholder='Please input'
            value={infoValues['policyNo']}
            onChange={this.policyChange}
            onBlur={this.searchPInfo}
          ><div dangerouslySetInnerHTML={{ __html: 'Policy No.' }} />
          </InputItem>
          {/* 其他因子 */}
          {this.keyCodes.map((item, index) =>
            <InputItem key={index}
              {...getFieldProps(item.keycode, {
                initialValue: infoValues[item.keycode] || '',
                rules: item.rules
              })}
              maxLength={50}
              labelNumber={5}
              type={item.type || ''}
              error={errorMap[item.keycode]}
              onErrorClick={() => this.onErrorClick(item.keycode)}
              placeholder='Please Input'
              disabled={this.state.disableInput}
            ><div dangerouslySetInnerHTML={{ __html: item.text }} /></InputItem>
          )}
        </List>

        {/* <!--被保险人选择--> */}
        {
          this.state.insuredArray.length > 0 ?
          <List className='input-list'>
              <Picker
                  {...getFieldProps('insuredId', {
                    initialValue: [this.state.insuredArray[0].value],
                    rules: [
                      { required: true, message: 'Must select a insured' }
                    ]
                  })}
                  cols={1}
                  data={this.state.insuredArray}
                  disabled={this.state.disableInput}
                >
                  <List.Item arrow='horizontal'>Insured</List.Item>
            </Picker>
         </List>:''
        }
         
         {/* 理赔金额输入 */}
        <List className='input-list'>
          <InputItem
            {...getFieldProps('claimAmount', {
              initialValue: infoValues['claimAmount'],
              rules: [
                { required: true, message: 'Please input amount' },
                { pattern: /[0-9.]*$/, message: 'The claim amount is not valid' }
              ],
              normalize: (v, prev) => {
                if (v && !/^(([1-9]\d*)|0)(\.\d{0,2}?)?$/.test(v)) {
                  if (v === '.') {
                    return '0.'
                  }
                  return prev
                }
                return v
              }
            })}
            placeholder='Please Input'
            maxLength={50}
            labelNumber={5}
            error={errorMap['claimAmount']}
            onErrorClick={() => this.onErrorClick('claimAmount')}
            disabled={this.state.disableInput}
          >
          <div className='flex-item' style={{ justifyContent: 'space-between' }}>Claim Amount<span className='fr fc69 strong'>$</span></div>
          </InputItem>
        </List>
        <p className='f26 fc9 pl30 pb30 pt30'>Accident Info</p>
        <List className='input-list'>
          {/* 险种选择 */}
          <Picker
            {...getFieldProps('claimType', {
              initialValue: ['1'],
              rules: [
                { required: true, message: 'Must select a claim type' }
              ]
            })}
            cols={1}
            data={Globle.claimTypes}
            error={errorMap['claimType']}
            onErrorClick={() => this.onErrorClick('Must select a claim type')}
            disabled={this.state.disableInput}
          >
          <List.Item arrow='horizontal'>Claim Types</List.Item>
          </Picker>

          {/* 日期选择 */}
          <div style={{ position: 'relative' }} >
            <DatePicker extra={'Please select the date'}
              {...getFieldProps('accidentDate', {
                initialValue: defaultDate,
                rules: [
                  { required: true, message: 'Must select a date' }
                ]
              })}
              mode='date'
              minDate={minDate}
              maxDate={nowDate}
              onOk={(val) => this.onDateOk(val)}
              format={this.dateFormat}
              
              onErrorClick={() => this.onErrorClick('Must select a date')}
              disabled={this.state.disableInput}
            >
              <List.Item arrow='horizontal'>Accident Date</List.Item>
            </DatePicker>
            {/* <div className='date-content'>{dateValue || ''}</div> */}
          </div>

        </List>

        <div className='bottom clearfix'>
          <Flex>
            <Flex.Item className='tac pt30 pb30 fcw f36 diy_background' style={{ flex: '1', borderRadius: '4px' }} onClick={this.handleSubmit}>Next</Flex.Item>
          </Flex>
        </div>
      </div>
    )
  }
}

const AppForm = createForm()(App)
export default AppForm
